package com.runvp.handler;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.core.redis.DistributeRedisLock;
import com.runvp.common.core.redis.RedisLockClient;
import com.runvp.common.enums.*;
import com.runvp.common.model.tcp.MessageReceiveBody;
import com.runvp.common.model.tcp.MessageResBody;
import com.runvp.common.util.ToolUtils;
import com.runvp.common.utils.DateUtils;
import com.runvp.service.biz.domain.BizOrder;
import com.runvp.service.biz.handler.CmdCommonHandler;
import com.runvp.service.out.OutUtil;
import com.runvp.service.tcp.TcpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
public class CmdDeviceResStartChargHandler1 {

    @Autowired
    private CmdCommonHandler cmdCommonHandler;
    @Autowired
    private RedisLockClient lockClient;
    @Autowired
    private TcpService tcpService;
    /**
     * 设备回应服务器发下发启动充电指令
     * @param parseBody
     * @return MessageResBody
     */
    @Transactional(rollbackFor = Exception.class)
    public MessageResBody handle(MessageReceiveBody parseBody){
        log.info("设备回应服务器下发启动充电指令处理:::receiveBody:{}",JSONObject.toJSONString(parseBody));
        String batchNo = System.nanoTime()+"";
        StringBuilder tips = new StringBuilder();
        tcpService.addBizTcpRecord(parseBody.setBatchNo(batchNo));
        JSONObject body = parseBody.getBodyJson();
        String oid = body.getString("oid");
        DistributeRedisLock redisLock = lockClient.getRedisLock("startChargOrder:"+oid);
        try {
            redisLock.lock();
            BizOrder order = tcpService.instanceIBizOrderService().selectBizOrderByOrderNo(oid);
            if(null == order){
                boolean startStatus = startStatus(body,tips, ToolUtils.toInt(oid));
                log.info("调试订单【{}】充电开启结果【{}】",oid,startStatus);
                if(startStatus){
                    tcpService.instanceIBizDeviceCargoService().usePort(ToolUtils.objTOLong(oid), CargoUseStatus.USE.getCode());
                    log.info("调试订单【{}】端口锁定成功",oid);
                }
            }else {
                boolean startStatus = startStatus(body,tips, order.getPort());
                log.info("常规订单【{}】充电开启结果【{}】",oid,startStatus);
                if(startStatus){
                    try {
                        if(PayChannel.PAY_CLOUD_CARD.getCode().equals(order.getType())){
                            //执行扣款
                            cmdCommonHandler.buildCustomerTranLog("刷卡充电: ",order);
                            order.setPayStatus(OrderPayStatus.PAY_SUCCESS.getCode());
                            order.setPayTime(DateUtils.getNowDate());
                            order.setPayAmount(order.getAmount());
                        }
                        order.setRemark(order.getRemark()+tips);
                        order.setStatus(OrderStatus.GO_ON.getCode());
                        //启用订单
                        order.setEnable(EnableStatus.ENABLE.getCode());
                        tcpService.instanceIBizOrderService().updateBizOrder(order);
                        //修改端口状态为使用中
                        tcpService.instanceIBizDeviceCargoService().usePort(order.getCargoId(), CargoUseStatus.USE.getCode());
                        log.info("常规订单【{}】端口锁定成功",oid);
                    }catch (Exception e){
                        //如果订单处理失败，则停止充电
                        JSONObject param = new JSONObject();
                        param.put("po",order.getPort());
                        param.put("oid", oid);
                        boolean res = OutUtil.stop(order.getDeviceSn(),param.toJSONString());
                        log.error("订单处理失败，发送停止充电指令结果:【{}】",res);
                    }

                }
            }
            log.info("设备回应服务器下发启动充电指令处理:::无需回应resBody: null");
        }catch (Exception e){
            log.error("常规订单【{}】充电开启异常【{}】",oid,e.getMessage());
        }finally {
            redisLock.unlock();
        }
        return null;
    }

    /**
     * 判断充电开启状态
     * @param body
     * @param tips
     * @param port
     * @return boolean
     */
    private boolean startStatus(JSONObject body,StringBuilder tips,Integer port){
        Integer rs = body.getInteger("rs");
        Integer er = body.getInteger("er");
        String msg = String.format("\n时间【%s】",DateUtils.getTime());
        //启动结果 1:成功 0：失败
        if(!rs.equals(1)){
            String errorMsg = msg+"启动充电失败:";
            ///错误码，0：无错误 1：故障 2：端口占用
            if(er.equals(1)){
                //1：故障
                errorMsg += "【端口"+port+" 故障】";
            }
            if(er.equals(2)){
                //2：端口占用
                errorMsg += "【端口"+port+" 占用】";
            }
            tips.append(errorMsg);
            log.info("设备回应服务器下发启动充电指令业务处理:{}",errorMsg);
            return false;
        }else {
            String succMsg = msg+"充电启动成功";
            tips.append(succMsg);
            log.info("设备回应服务器下发启动充电指令业务处理:{}",succMsg);
            return true;
        }
    }
}
